<template>
  <div class="table-container-inner">
    <div class="table-height">
      <el-table
        :height="'800px'"
        v-loading="loading"
        :data="dataList"
        border
        size="medium"
        @selection-change="handleSelectionChange"
        :cell-style="cellStyle"
        class="table-fixed"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          v-for="item in viewData"
          :key="item.ctTitle"
          :min-width="item.ctWide.indexOf('%') > 0 ? item.ctWide: 0"
          :width="item.ctWide.indexOf('%') > 0 ? 0: item.ctWide"
          :prop="item.ctName"
          :label="item.ctTitle"
          :align="item.ctAlign"
          header-align="center"
          show-overflow-tooltip
          :scoped-slot="labelHead"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          label="操作"
          :show-overflow-tooltip="false"
          align="center"
          class-name="small-padding fixed-width"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              v-show="checkPermission([permissionPrefix + 'query']) && showButton == 'query'"
              type="text"
              size="medium"
              icon="el-icon-postcard"
              v-hasPermi="[permissionPrefix + 'query']"
              @click="handleQuery(scope.row)"
              title="查看"
            ></el-button>
            <el-button
              v-show="checkPermission([permissionPrefix + 'sign']) && showButton == 'sign'"
              type="text"
              size="medium"
              icon="el-icon-edit"
              v-hasPermi="[permissionPrefix + 'sign']"
              @click="handleSign(scope.row)"
              title="签发"
            ></el-button>
            <el-button
              v-show="checkPermission([permissionPrefix + 'edit']) && showButton == 'edit'"
              type="text"
              size="medium"
              icon="el-icon-edit-outline"
              v-hasPermi="[permissionPrefix + 'edit']"
              @click="handleUpdate(scope.row)"
              title="编辑"
            ></el-button>
            <el-button
              v-show="checkPermission([permissionPrefix + 'remove']) && funNo != '1000'"
              type="text"
              size="medium"
              icon="el-icon-delete"
              v-hasPermi="[permissionPrefix + 'remove']"
              @click="handleDelete(scope.row)"
              title="删除"
            ></el-button>
            <el-button
              v-show="checkPermission([permissionPrefix+'file'])"
              type="text"
              size="medium"
              icon="el-icon-view"
              v-hasPermi="[permissionPrefix + 'file']"
              @click="handleFile(scope.row)"
              title="预览附件"
              v-if="scope.row.blob"
            ></el-button>
            <el-button
              v-show="checkPermission([permissionPrefix+'file'])"
              type="text"
              size="medium"
              icon="el-icon-view"
              v-hasPermi="[permissionPrefix + 'file']"
              disabled
              title="没有可预览的附件"
              v-else
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="审批" :visible.sync="approveInfoOpen" width="600px">
      <el-form
        ref="approveInfoForm"
        :model="approveInfoForm"
        :rules="approveInfoRules"
        label-width="80px"
      >
        <el-form-item label="审批意见" prop="reason">
          <el-input
            v-model="approveInfoForm.reason"
            type="textarea"
            placeholder="请输入审批意见"
            rows="4"
            resize="none"
          />
        </el-form-item>
        <el-form-item label="审批" prop="type">
          <el-radio-group v-model="approveInfoForm.type">
            <el-radio value="01" label="01">同意</el-radio>
            <el-radio value="02" label="02">退回</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="approveCancel">取 消</el-button>
        <el-button type="primary" @click="submitApproveInfoForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { checkPermi } from '@/utils/permission.js'
  import { tableData, delmisTableData } from './tableData'
  import { setFinishMessage } from '@/api/spsMyInfo/message'
  import store from '@/store/index'
  import { getFunNo } from '@/utils/party'
 // import { taskList } from '@/api/spsFirst/spsFirst.js'
  import { batchSign } from '@/components/SpsPublic/SignList/SignList'
  import {NAME} from '@/utils/config'
  export default {
    name: 'dynamiclist',
    props: {
      // 组件需要获取的值
      viewData: {
        type: Array,
        default: () => {
          return []
        },
      },
      // 查询参数
      queryParams: {
        type: Object,
        default: () => {
          return {}
        },
      },
      permissionPrefix: {
        type: String,
        default: () => {
          return 'dynamic:button:'
        },
      },
      taskreportList:{
        default:true,
        type:Boolean
      }
    },
    data() {
      return {
        store: store,
        // 表格数据
        dataList: null,
        loading: true,
        // 选中数组
        ids: [],
        tableList: [],
        total: 0,
        funNo: getFunNo(this.taskreportList ?this.$route : this.$router.resolve({ name: NAME }).route),
        tableHeight: 0,
        showButton: 'edit',
        singleStore: null,
        viewType: (this.taskreportList ?this.$route : this.$router.resolve({ name: NAME }).route).name.slice(-5).substring(0, 1),
        approveInfoOpen: false,
        approveInfoForm: {
          reason: '同意',
          type: '01',
        },
        approveInfoRules: {
          reason: [
            {
              required: true,
              message: '审批意见不能为空',
              trigger: 'blur',
            },
          ],
        },
      }
    },
    computed: {
      isChangeCellStyle() {
        return (
          typeof this.viewData.find((q) => q.ctName == 'ct_end_name') !=
          'undefined'
        )
      },
    },
    created() {
      console.log(this.taskreportList);
      this.showButtonAction(this.permissionPrefix)
      this.singleStore = store.getters.singleStore['main' + this.funNo]
    },
    updated() {
      // myTable是表格的ref属性值
      if (this.$refs.myTable && this.$refs.myTable.doLayout) {
        this.$refs.myTable.doLayout()
      }
    },
    watch: {
      permissionPrefix: function (newVal, oldVal) {
        this.showButtonAction(newVal)
      },
    },
    methods: {
      sortChange(sortInfo) {
        this.queryParams.orderByColumn = sortInfo.prop
        if (sortInfo.order === 'descending') {
          this.queryParams.isAsc = 'desc'
        } else {
          this.queryParams.isAsc = 'asc'
        }
        this.getList(this.queryParams)
      },
      // 提交批量签发信息
      submitApproveInfoForm() {
        this.approveInfoForm.ctIdList = this.ids
        this.approveInfoForm.funNo = this.funNo
        batchSign(this.approveInfoForm).then((response) => {
          if (response.code === 200) {
            this.$message.success(response.msg)
            this.approveInfoOpen = false
            this.getList()
            return
          }
          this.$message.error(response.msg)
        })
      },
      // 取消按钮
      approveCancel() {
        this.approveInfoOpen = false
      },
      // 批量签发
      handleBatchSign(row) {
        if (!row && this.ids.length < 1) {
          this.$message.warning('请先选择需签发的条目')
          return
        }
        // 打开签发dialog
        this.approveInfoOpen = true
      },
      // 显示按钮判断
      showButtonAction(newVal) {
        if (this.funNo == '9527' || this.$route.name.indexOf('S') !== -1) {
          this.showButton = 'sign'
          return
        }
        const editPerm = this.checkPermission([newVal + 'edit'])
        const queryPerm = this.checkPermission([newVal + 'query'])
        if (editPerm) {
          this.showButton = 'edit'
          return
        }
        if (this.funNo == '8501' || (!editPerm && queryPerm)) {
          this.showButton = 'query'
        }
      },
      labelHead(h, { column, index }) {
        let l = column.label.length
        let f = 16 //每个字大小，其实是每个字的比例值，大概会比字体大小差不多大一点，
        column.minWidth = f * l //字大小乘个数即长度 ,注意不要加px像素，这里minWidth只是一个比例值，不是真正的长度 //然后将列标题放在一个div块中，注意块的宽度一定要100%，否则表格显示不完全
        return h('div', { class: 'table-head', style: { width: '100%' } }, [
          column.label,
        ])
      },
      cellStyle(data) {
        let style = 'padding:0px;'
        if (!this.isChangeCellStyle) {
          return style
        }
        if (data.columnIndex == 1) {
          if (data.row.ct_end_name && data.row.ct_end_name == '未签发') {
            style += 'color:#f95a5a;'
          } else if (data.row.ct_end_name && data.row.ct_end_name == '已签发') {
            style += 'color:#21bd21;'
          }
        }
        return style
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.ct_id)
        this.ctNames = selection
          .filter((item) => item.ct_name && item.ct_name && item.ct_name !== '')
          .map((item) => item.ct_name)
        this.ctNames = this.ctNames.join(',')
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 检查权限
      checkPermission(permissions) {
        const flag = checkPermi(permissions)
        return flag
      },
      // 获取列表
      getList() {
        this.refreshFlag = false
        this.refreshFlag = true
        this.loading = true
        if (this.funNo === '8502') {
          taskList(this.queryParams)
            .then((response) => {
              this.dataList = response.data
              this.total = 10
              this.loading = false
            })
            .catch(() => {
              this.loading = false
              this.dataList = []
              this.total = 0
            })
          return
        }
        tableData(this.queryParams)
          .then((response) => {
            this.dataList = response.rows
            this.total = response.total
            this.loading = false
          })
          .catch(() => {
            this.loading = false
            this.dataList = []
            this.total = 0
          })
      },
      // 删除
      handleDelete(row) {
        if (!row && this.ids.length < 1) {
          this.$message.warning('请先选择需删除的条目')
          return
        }
        const params = {
          funNo: this.funNo,
        }
        let ctName = '是否确认删除记录 '
        // 单条删除
        if (row) {
          params.bussId = [row.ct_id]
          if (row.ct_name) {
            ctName += row.ct_name
          }
        } else {
          // 多条删除
          params.bussId = this.ids
          ctName += this.ctNames
        }
        this.$confirm(ctName + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          delmisTableData(params).then((response) => {
            if (response.code == 200) {
              this.msgSuccess(response.msg)
            } else {
              this.msgError(response.msg)
            }
            this.getList()
          })
        })
      },
      // 单条签字
      handleSign(row) {
        row.handleType = 'sign'
        this.handleAction(row)
      },
      // 修改
      handleUpdate(row) {
        row.handleType = 'edit'
        this.handleAction(row)
      },
      // 查看
      handleQuery(row) {
        row.handleType = 'view'
        this.handleAction(row)
      },
      // handle 动作函数
      handleAction(row) {
        switch (this.viewType) {
          case 'Q':
            row.handleType = 'view'
            break
          case 'A':
            if (row.handleType != 'view') {
              row.handleType = 'edit'
            }
            break
          case 'S':
            row.handleType = 'sign'
            break
          default:
            break
        }
        if (this.funNo === '8502') {
          row.ct_fun_no = row.ctFunNo
          row.ct_id = row.ctId
        }
        if (typeof row.ct_fun_no === 'undefined') {
          row.ct_fun_no = this.funNo
        }
        const handleTypeModel = {
          funNo: this.funNo,
          handleType: row.handleType,
        }
        store.dispatch('setHandleType', handleTypeModel).then(() => {
          this.$emit('updateValue', row)
        })
        store.dispatch('openShowMaster', this.funNo)
        if (row.ct_buss_id) {
          row.ct_id = row.ct_buss_id
        }

        const subSingleStore = {
          funNo: this.funNo,
          subFunNo: row.ct_fun_no,
          oldForm: {},
          newForm: {},
          ctId: row.ct_id,
          changeForm: false,
          ifEnd: row.ct_end_name == '已签发',
        }
        // 初始化subSingleStore
        store.dispatch('createSubSingleStore', subSingleStore).then(() => {
          store.dispatch('setCtId', subSingleStore)
        })
        const tMisMessage = {
          ctFunNo: row.ct_fun_no,
          ctBussId: row.ct_id,
        }
        setFinishMessage(tMisMessage)
      },
      // 附件预览 (需要在视图中增加左链接第一个附件id(ct_blob_id) ,如果存在才可以显示，否则提示不存在附件）
      // TODO: 根据bussId判断是否有附件
      handleFile(row) {
        if (row.ct_fun_no == undefined) {
          row.ct_fun_no = this.funNo
        }
        // 这里处理是否包含附件字段，如果不包含，则忽略
        if (!('ct_blob_id' in row)) {
          this.msgInfo('未配置附件显示信息，请联系管理员')
        } else {
          let blobid = row.ct_blob_id
          if (blobid) {
            store.dispatch('setFilePreview', row).then(() => {
              this.$router.push({ path: '/SpsPublicRouter/FilePreview' })
            })
          } else {
            this.msgInfo('附件不存在')
          }
        }
      },
    },
  }
</script>

<style lang='scss' scoped>
  ::v-deep.table-head {
    font-size: 14px !important;
  }
  .table-container-inner {
    // position: absolute;
    // left: 0;
    // right: 0;
    // top: 0;
    width: 100%;
    height: 100%;
    .table-height {
      height: calc(100% - 70px);
    }
  }
  ::v-deep.el-table__body-wrapper {
    height: calc(100% - 44px) !important;
  }

  .table-fixed {
    overflow: auto;
  }
</style>
